const path = require("path");
const db = require(path.join(__dirname,'./../middleware/mysql/db'));
var dataresult = require(path.join(__dirname,'./../module/dataresult'));
const plugm = require(path.join(__dirname,'./../module/plug'));

function queryPlug(params) {
    return new Promise(async function(resolve, reject){
        try{
            let whereparam = "";
            if(params.id!="" || typeof(params.id)!="undefined"){
                whereparam = [{key:"id",value:params.id}]
            }
            let sql = await db.getSelect(params,plugm.colum,plugm.tablename,whereparam);
            await db.query(sql, function (err, rows) {
                dataresult.succSearch(rows);
                err ? reject(err) : resolve(dataresult)
            });
        }catch(err){
            console.log(err);
            resolve("查询插件时抛出异常");
        }
    })
}

function savePlug(params) {
    return new Promise((resolve, reject) => {
        try{
            console.log(params);
            let sql = db.getInsert(params,plugm.colum,plugm.tablename);
            db.query(sql, function (err, rows) {
                dataresult.succExec(rows);
                err ? reject(err) : resolve(dataresult)
            });
        }catch(err){
            console.log(err);
            resolve("保存插件时抛出异常");
        }
    })
}

function updatePlug(params) {
    return new Promise((resolve, reject) => {
        try{
            console.log(params);
            if(!params.id){
                reject("修改的数据id为空，请检查");
            }
            let sql = db.getUpdate(params,plugm.colum,plugm.tablename);
            db.query(sql, function (err, rows) {
                dataresult.succExec(rows);
                err ? reject(err) : resolve(dataresult)
            });
        }catch(err){
            console.log(err);
            resolve("更新插件后台抛出异常");
        }
    })
}

function deletePlug(params) {
    return new Promise((resolve, reject) => {
        try{
            if(!params.id){
                reject("删除的数据id为空，请检查");
            }
            let sql = db.getDelete(params,plugm.colum,plugm.tablename);
            db.query(sql, function (err, rows) {
                dataresult.succExec(rows);
                err ? reject(err) : resolve(dataresult)
            });
        }catch(err){
            console.log(err);
            resolve("删除插件后台抛出异常");
        }
    })
}

exports.queryPlug = queryPlug;
exports.savePlug = savePlug;
exports.updatePlug = updatePlug;
exports.deletePlug = deletePlug;